(function(){
    'use strict'

    var app = angular.module('app');

    app.directive('setNum', SetNum);        //设置dashboard的数字
	app.directive('setTime',SetClock);      //设置dashboard的实时时间
    app.directive('infoBoard',InfoBoard);   //车辆数据大屏滚动报警信息
    app.directive('resizeLayout',ResizeLayout);

    ResizeLayout.$inject = ['DashboardService'];
    function ResizeLayout(DashboardService){
        return {
            restrict:'A',
            link:function(scope, elem, attrs){
                $(elem).resize(DashboardService.flexLayout);
            }
        }
    };

    //设置dashboard的实时时间
	SetClock.$inject = ['$timeout'];
	function SetClock($timeout){
		function clock(){
			var t= null;
				var _Date = new Date(),
					_year = _Date.getFullYear(),
					_month = _Date.getMonth()+1,
					_date = _Date.getDate(),
					_hours = _Date.getHours(),
					_minu = _Date.getMinutes(),
					_sec = _Date.getSeconds();
		
				t = (function(mon,date,hour,minu,sec){
					mon <10 ? mon ='0'+mon : mon;
					date <10 ? date = '0'+date : date;
					hour < 10 ? hour = '0'+hour : hour;
					minu < 10 ? minu = '0'+minu : minu;
					sec < 10 ? sec = '0'+sec : sec;
					
					return _year+'-'+mon+'-'+date+' '+hour+':'+minu+':'+sec;
				})(_month,_date,_hours,_minu,_sec)
				
				return t;
		};
		return {
			restrict:'A',
			link:function(scope,elem,attrs){
				var timer = null;
				clearTimeout(timer);
				timer = $timeout(function settime(){
					var nowtime = clock();
					$(elem).html(nowtime);
					$timeout(settime,1000)
				},1000)
			}
		}
	}
    //设置dashboard的数字
	SetNum.$inject = ['$http','$timeout'];
	function SetNum($http, $timeout){
			/*
			* 设置千分位
			*/
			function formaterNum(val,_style){  
				var reg=/(?=(?!\b)(\d{3})+$)/g;  
				var numType = typeof val;
				var num = val*1,
					countDown = num/100,
					styleText ='',
					newNum = '',
					str = '';

				if(numType == 'string'){
					newNum = String(num).replace(reg, ',');  
				}else{
					newNum = String(num);
				}
				
				if(_style&& Object.prototype.toString.call(_style)  == "[object Object]"){
					for(var _attr in _style){
						styleText += _attr+':'+_style[_attr]+';';
					}
				}	   
			
				for(var i=0,len=newNum.length;i<len;i++){
					if(newNum[i] != ''){
						if(styleText != ''){
							str += '<span style="'+styleText+'">'+newNum[i]+'</span>';
						}else{
							str += '<span style="display:inline-block;font-size:20px;color:#fff;">'+newNum[i]+'</span>';
						}

					}
				}
				
				return str;
			}; 
			//数字动画
			function countDown(initnum, subtrahend, _style, callback){
				var numStyle = typeof initnum;
				var initnum = parseFloat(initnum);
				var s = parseFloat(subtrahend) || 0;
				var box = 0;
				var timer = null;
				var cnt = 0;
				var callback = Array.prototype.slice.call(arguments,-1)[0];
				var _style = Array.prototype.slice.call(arguments,-2)[0];
				var startTime = new Date().getTime();

				function getNumType(val){
					if(numStyle == 'string'){
						return val+'';
					}else{
						return val;
					}
				}

				typeof _style == 'object' ? _style = _style : _style = null;
				clearTimeout(timer);
				timer = setTimeout(function countdown(){
				
					if(cnt ==  initnum || s !=0 && cnt == s){
						clearTimeout(timer);
						return false;
					}
					var timestamp = new Date().getTime();
					var progress = timestamp - startTime;
					if(s && typeof s == 'number'){
						cnt = 0 - ((0 - s) * (progress / 2500));
						cnt = Math.round(cnt*1)/1;
						cnt = (cnt > Math.abs(s)) ? s : cnt;
						
						callback.call(this,formaterNum(getNumType(initnum+cnt),_style));
					}else{
						cnt = 0 - ((0 - initnum) * (progress / 2500));
						cnt = Math.round(cnt*1)/1;
						cnt = (cnt > initnum) ? initnum : cnt;
						
						callback.call(this,formaterNum(getNumType(cnt),_style));
					}
			
					setTimeout(countdown,0);
				},0)
			};
		return {
			restrict:'A',
			link:function(scope,elem,attrs){
				
				var textStyle = {
					'display':'inline-block',
					'margin-right':'4px',
					'padding':'2px 4px',
					'background':'rgba(90,200,250,0.2)',
					'font-size':'36px',
					'color':'#fff'
				};
				var count = parseFloat(attrs.getCont);
				var contstyle = scope.$eval(attrs.contStyle) || {};
		
				$.extend(textStyle,contstyle)
				countDown(count, textStyle, function(num){$(elem).html(num)});

				scope.$watch(attrs.getCont,function(){
					
					console.log('test-修改数据')
				})
			}
		}
	};

    //车辆数据大屏滚动报警信息
    InfoBoard.$inject = ['$timeout'];
    function InfoBoard($timeout){
        //设置数据滚动
        var scrollData = function(settings){
            this.settings = $.extend(true, {dur:1,dis:36}, settings);
            this.wrap = null;
            this.eq = 0;
            this.actualLen = 0;
            this.capacity = 0;
        }
        scrollData.fn = scrollData.prototype;

        //执行滚动主程序
        scrollData.fn.scroll = function(){
            var self = this;
            var _children = [],
                len = self.capacity;
            
            if(self.actualLen <= len){
                return false;
            }
            
            //保存第一屏的数据
            for(var i=0;i<len+1;i++){
                _children.push(self.wrap.children().eq(i))
            }
            //执行滚动
            $.each(_children, function(index,child) {
                child.animate({
                    'height':'0px',
                },"slow",function(){
                    $(this).height('36px');
                    $(this).appendTo(self.wrap);
                });
            });

            self.on();
        };
        //开启滚动
        scrollData.fn.on = function(){
            var dur = 1,
                self = this;
            self.run = null;
            clearTimeout(self.run);
            self.run = setTimeout(function(){
                self.scroll(dur);
            },3000);
        };
        //关闭滚动
        scrollData.fn.off = function(){
            var self = this;
            if(self.run != 'undefined')clearTimeout(self.run);
        };
        //添加数据到容器
        scrollData.fn.addData = function(results){
            var self = this;
            var $wrap = self.wrap;
            this.capacity = Math.round($wrap.parent().height()/self.settings.dis);//获取容器能显示的数据条数
            if(results && typeof results =='object'){

                $.each(results,function(index,obj){
                    var dataRow = $('<div class="scroll-data-row"></div>');
                    dataRow.css({
                        'height':self.settings.dis+'px',
                        'width':'100%'
                    });
                    $.each(obj, function(key,value) {
                        var dataCol = $('<div class="scroll-data-col"></div>');
                        dataCol.html(value);
                        dataRow.append(dataCol);
                    });
                    
                    if(self.actualLen <= self.capacity){
                        self.actualLen ++;
                    }
                    
                    $wrap.append(dataRow);

                });
                
            };	
            //如果未开启数据滚动，则开启
            if(!self.run){
                self.on();
            }
        };
        //获取容器下的数据条数
        scrollData.fn.queryLength = function(){
            return this.wrap.children().size();
        };
        //创建数据容器
        scrollData.fn.createDataWrap = function(){
            if(this.wrap){
                return this.wrap;
            }
            var $wrap = this.wrap = $('<div></div>'),
                self = this;
            $wrap.css({
                'position':'absolute',
                'top':'0px',
                'left':'0px',
                'width':'100%'
            });
            //鼠标移出执行数据滚动
            $wrap.mouseover(function(){
                self.off();
            });
            //鼠标移入停止数据滚动
            $wrap.mouseout(function(){
                if(self.run){
                    self.on();
                }
            });
            
        /*	if(this.queryLength*self.settings.dis > $wrap.height()){
                self.off();
                self.on();
            }*/
            
            return $wrap;
        };

        return {
            restrict:'A',
            link:function(scope, elem, attrs){
                var timer = null;
                var data = [[{"报警类型":"停车报警","车辆":"111111"},{"报警类型":"停车报警","车辆":"111111"},{"报警类型":"停车报警","车辆":"111111"},{"报警类型":"停车报警","车辆":"111111"},{"报警类型":"超速报警","车辆":"111111"},{"报警类型":"停车报警","车辆":"111111"},{"报警类型":"停车报警","车辆":"111111"},{"报警类型":"停车报警","车辆":"111111"}],[{"报警类型":"停车报警","车辆":"222222"},{"报警类型":"停车报警","车辆":"222222"},{"报警类型":"停车报警","车辆":"222222"},{"报警类型":"停车报警","车辆":"222222"},{"报警类型":"停车报警","车辆":"222222"},{"报警类型":"超速报警","车辆":"222222"},{"报警类型":"停车报警","车辆":"222222"},{"报警类型":"停车报警","车辆":"222222"}],[{"报警类型":"停车报警","车辆":"333333"},{"报警类型":"停车报警","车辆":"333333"},{"报警类型":"停车报警","车辆":"333333"},{"报警类型":"停车报警","车辆":"333333"},{"报警类型":"停车报警","车辆":"333333"},{"报警类型":"超速报警","车辆":"333333"},{"报警类型":"停车报警","车辆":"333333"},{"报警类型":"停车报警","车辆":"333333"}],[{"报警类型":"停车报警","车辆":"444444"},{"报警类型":"停车报警","车辆":"444444"},{"报警类型":"停车报警","车辆":"444444"},{"报警类型":"停车报警","车辆":"444444"},{"报警类型":"停车报警","车辆":"444444"},{"报警类型":"超速报警","车辆":"444444"},{"报警类型":"停车报警","车辆":"444444"},{"报警类型":"停车报警","车辆":"444444"}]];
                var infoBoard = new scrollData();
                var infoWrap = infoBoard.createDataWrap();
                var counter = 0;
                $(elem).append(infoWrap);

                $timeout(function addInfo(){
                    infoBoard.addData(data[counter]);
                    $timeout(addInfo,2000);
                    counter ++;
                },2000);
            }
        }

    }

})();